//
//  DZMRMColorView.swift
//  DZMeBookRead
//
//  Created by 邓泽淼 on 2017/5/11.
//  Copyright © 2017年 DZM. All rights reserved.
//
import UIKit

class DZMRMColorView: DZMRMBaseView {
    
    /// 颜色数组
    private var colors = [UIColor]()
    
    /// 选中索引
    private var selectIndex = 0
    
    /// 初始化方法
    init(frame:CGRect,readMenu:DZMReadMenu,colors:[UIColor],selectIndex:Int) {
        self.colors = colors
        self.selectIndex = selectIndex
        super.init(frame: frame, readMenu: readMenu)
    }
    
    // MARK: -- 有抖动效果
    
    /// 选中按钮
    private var selectButton:DZMHaloButton?
    
    override func addSubviews() {
        
        // 创建颜色按钮
        let count = colors.count
        
        // 设置的index大于颜色数组
        if selectIndex >= count {selectIndex = 0}

        let PublicButtonWH:CGFloat = DZMHaloButton.HaloButtonSize(CGSize(width: 39, height: 39)).width
        
        let spaceW:CGFloat = (UIScreen.main.width - 2 * CGFloat.readerSpace._1 - CGFloat(count) * PublicButtonWH) / CGFloat(count - 1)
        
        for i in 0..<count {
            
            let color = colors[i]
            
            let publicButton = DZMHaloButton(CGRect(x: CGFloat.readerSpace._1 + CGFloat(i) * (PublicButtonWH + spaceW), y: CGFloat.readerSpace._1, width: PublicButtonWH, height: PublicButtonWH), haloColor:color)
            
            publicButton.tag = i
            
            publicButton.imageView.backgroundColor = color
            
            addSubview(publicButton)
            
            publicButton.addTarget(self, action: #selector(DZMRMColorView.clickButton(button:)), for: .touchUpInside)
            
            if selectIndex == i {
                
                selectButton(button: publicButton)
            }
        }
        
    }
    
    /// 点击按钮
    @objc private func clickButton(button:DZMHaloButton) {
        guard let readMenu_ = self.readMenu else { return }
        self.selectButton(button: button)
        self.readMenu?.delegate?.readMenuClickSetuptColor?(readMenu: readMenu_, index: button.tag, color: colors[button.tag])
    }
    
    /// 选中按钮
    private func selectButton(button:DZMHaloButton) {
        
        selectButton?.imageView.layer.borderColor = UIColor.clear.cgColor
        selectButton?.imageView.layer.borderWidth = 0
        
        button.imageView.layer.borderColor = UIColor.cj.color_2.cgColor
        button.imageView.layer.borderWidth = 2.0
        
        selectButton = button
    }
    
    required init?(coder aDecoder: NSCoder) {
        
        fatalError("init(coder:) has not been implemented")
    }
}
